# Description: a simple student management system
# Author: chengzhen
# Date: 2021/9/27 8:01 下午
# Debug the code, debug the world!
import os

fileName = "student.txt"


def menu():
    print("====================学生信息管理系统=======================")
    print("---------------------功能管理菜单--------------------------")
    print("\t\t\t\t\t\t1.录入学生信息\t\t\t\t\t\t")
    print("\t\t\t\t\t\t2.查找学生信息\t\t\t\t\t\t")
    print("\t\t\t\t\t\t3.删除学生信息\t\t\t\t\t\t")
    print("\t\t\t\t\t\t4.修改学生信息\t\t\t\t\t\t")
    print("\t\t\t\t\t\t5.排序\t\t\t\t\t\t")
    print("\t\t\t\t\t\t6.统计学生总人数\t\t\t\t\t\t")
    print("\t\t\t\t\t\t7.显示所有学生信息\t\t\t\t\t\t")
    print("\t\t\t\t\t\t0.退出系统\t\t\t\t\t\t")
    print("----------------------------------------------------------")


def main():
    while True:
        menu()
        try:
            choice = int(input("请选择:"))
        except BaseException as e:
            print("请输入可选项数字，错误原因:" + str(e))
        else:
            if choice in [0, 1, 2, 3, 4, 5, 6, 7]:
                if choice == 0:
                    answer = input("您确定要退出系统吗？y/n\n")
                    if answer == 'y' or answer == 'Y':
                        print("谢谢您的使用!!!")
                        break
                    else:
                        continue
                elif choice == 1:
                    insert()
                elif choice == 2:
                    search()
                elif choice == 3:
                    delete()
                elif choice == 4:
                    update()
                elif choice == 5:
                    sort()
                elif choice == 6:
                    total()
                elif choice == 7:
                    show()


def insert():
    student_list = []
    while True:
        sid = input("请输入ID（如1001）:")
        if not sid:
            break
        name = input("请输入姓名:")
        if not name:
            break
        english_score = ''
        python_score = ''
        java_score = ''
        while True:
            try:
                english_score = int(input("请输入英语成绩:"))
                python_score = int(input("请输入Python成绩:"))
                java_score = int(input("请输入Java成绩:"))
            except ValueError:
                print("输入无效，不是整数类型，请重新输入")
                continue
            else:
                break
        # 将输入的学生的成绩保存到字典中
        student = {"id": sid, "name": name, "english_score": english_score, "python_score": python_score,
                   "java_score": java_score}
        # 将学生信息添加到列表中
        student_list.append(student)
        answer = input("是否继续添加？Y/N\n")
        if answer == "y" or answer == "Y":
            continue
        else:
            break
    save(student_list)
    print("学生信息录入完毕!!!")


def save(lst):
    try:
        file = open(fileName, "a", encoding="utf-8")
    except FileNotFoundError:
        file = open(fileName, "w", encoding="utf-8")
    for item in lst:
        file.write(str(item) + "\n")
    file.close()


def search():
    student_query = []
    while True:
        sid = ''
        name = ''
        if os.path.exists(fileName):
            mode = input("按id查找请输入1, 按姓名查找请输入2:")
            if mode == "1":
                sid = input("请输入学生id:")
            elif mode == "2":
                name = input("请输入学生姓名:")
            else:
                print("您的输入有误，请重新输入:")
                search()
                return
            with open(fileName, "r", encoding="utf-8") as rf:
                student_old = rf.readlines()
                for item in student_old:
                    d = dict(eval(item))
                    if sid != '':
                        if sid == d.get("id"):
                            student_query.append(d)
                    elif name != '':
                        if name == d.get("name"):
                            student_query.append(d)
            # 显示查询结果
            show_students(student_query)
            # 清空列表
            student_query.clear()
            answer = input("是否要继续查询？y/n\n")
            if answer == "y" or answer == "Y":
                continue
            else:
                break
        else:
            print("没有学生信息可以查询!!!")
            return


def show_students(lst):
    if len(lst) == 0:
        print("没有查询到学生信息，无数据显示!!!")
        return
    #  定义标题显示格式
    format_title = '{:^6}\t{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^8}'
    print(format_title.format("ID", "姓名", "英语成绩", "Python成绩", "Java成绩", "总成绩"))
    #  定义内容的显示格式
    format_data = '{:^6}\t{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^8}'
    for item in lst:
        print(format_data.format(
            item.get('id'),
            item.get('name'),
            item.get('english_score'),
            item.get('python_score'),
            item.get('java_score'),
            int(item.get('english_score')) + int(item.get('python_score')) + int(item.get('java_score'))))


def delete():
    while True:
        student_id = input("请输入要删除的学生的Id(如1001):")
        if student_id:
            if os.path.exists(fileName):
                with open(fileName, "r", encoding="utf-8") as rf:
                    student_old = rf.readlines()
            else:
                student_old = []
            flag = False  # 标记是否删除
            if student_old:
                with open(fileName, "w", encoding="utf-8") as wf:
                    for item in student_old:
                        d = dict(eval(item))  # 将字符串转化成字典
                        if d.get("id") != student_id:
                            wf.write(str(item))
                        else:
                            flag = True
                    if flag:
                        print(f"id为{student_id}的学生信息已被删除")
                    else:
                        print(f"没有找到id为{student_id}的学生的信息")
            else:
                print("没有学生信息!!!")
                break
            show()  # 删完之后重新显示所有学生信息
            answer = input("是否继续删除？Y/N\n")
            if answer == "Y" or answer == "y":
                continue
            else:
                break


def update():
    while True:
        show()
        student_id = input("请输入要修改的学生的id(如1001):")
        if student_id:
            if os.path.exists(fileName):
                with open(fileName, "r", encoding="utf-8") as rf:
                    student_old = rf.readlines()
            else:
                student_old = []
            if student_old:
                with open(fileName, "w", encoding="utf-8") as wf:
                    for item in student_old:
                        d = dict(eval(item))
                        sid = d.get("id")
                        flag = False  # 记录是否根据id查找到学生
                        if sid == student_id:
                            print("找到这名学生可以修改他的相关信息了！")
                            flag = True
                            name = input("请输入姓名:")
                            while True:
                                try:
                                    english_score = int(input("请输入英语成绩:"))
                                    python_score = int(input("请输入Python成绩:"))
                                    java_score = int(input("请输入Java成绩:"))
                                except ValueError:
                                    print("输入成绩有误，请重新输入")
                                    continue
                                else:
                                    break
                            student_updated = {"id": sid, "name": name, "english_score": english_score,
                                               "python_score": python_score, "java_score": java_score}
                            wf.write(str(student_updated) + "\n")
                        else:
                            wf.write(str(item))
                    if flag:
                        print("修改成功!!!")
                        answer = input("是否继续修改其他学生信息？Y/N")
                        if answer == "Y" or answer == "y":
                            continue
                        else:
                            break
                    else:
                        print(f"未查找到id为{student_id}的学生，请重新输入")


def sort():
    student_query = []
    if os.path.exists(fileName):
        with open(fileName, "r", encoding="utf-8") as rf:
            student_old = rf.readlines()
            if student_old:
                for item in student_old:
                    d = dict(eval(item))
                    student_query.append(d)
            else:
                print("没有学生数据信息可展示")
                return
    else:
        print("没有学生数据信息可展示")
        return
    # 记录排序方式以及排序字段
    asc_or_desc = input("请选择(0.升序，1.降序):")
    if asc_or_desc == "0":
        desc = False
    elif asc_or_desc == "1":
        desc = True
    else:
        print("您的输入有误，请重新输入")
        sort()
        return
    mode = input("请选择排序方式(1.按英语成绩排 2.按Python成绩排序 3.按Java成绩排序 0.按总成绩排序):")
    if mode == "1":
        student_query.sort(key=lambda x: x["english_score"], reverse=desc)
    elif mode == "2":
        student_query.sort(key=lambda x: x["python_score"], reverse=desc)
    elif mode == "3":
        student_query.sort(key=lambda x: x["java_score"], reverse=desc)
    elif mode == "0":
        student_query.sort(key=lambda x: int(x["english_score"])+int(x["python_score"])+(x["java_score"]), reverse=desc)
    else:
        print("您的输入有误，请重新输入")
        sort()
        return
    show_students(student_query)


def total():
    if os.path.exists(fileName):
        with open(fileName, "r", encoding="utf-8") as rf:
            lines = rf.readlines()
            if lines:
                print(f"一共有{len(lines)}名学生")
            else:
                print("还没有录入学生信息")
    else:
        print("暂未保存数据信息")


def show():
    query_student = []
    if os.path.exists(fileName):
        with open(fileName, "r", encoding="utf-8") as rf:
            student_old = rf.readlines()
            if student_old:
                for item in student_old:
                    d = dict(eval(item))
                    query_student.append(d)
                show_students(query_student)
    else:
        print("暂未保存数据信息")


if __name__ == "__main__":
    main()
